<template>
  <!-- 文件列表展示 -->
  <div>
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      {{ fileList }}
      <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
        <el-link :href="`${baseUrl}${file.url}`" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(file.url) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action" v-if="showDelBtn">
          <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
        </div>
      </li>
    </transition-group>
  </div>
</template>

<script>
  export default {
    props: {
      // 值
      value: [String, Object, Array],
      // 文件类型, 例如['png', 'jpg', 'jpeg']
      fileType: {
        type: Array,
        default: () => ['doc', 'xls', 'ppt', 'txt', 'pdf', 'mp4'],
      },
      // 是否展示删除按钮
      showDelBtn: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        baseUrl: process.env.VUE_APP_BASE_API,
        fileList: [],
      };
    },
    watch: {
      value: {
        handler(val) {
          if (val) {
            let temp = 1;
            // 首先将值转为数组
            const list = Array.isArray(val) ? val : this.value.split(',');
            // 然后将数组转为对象数组
            this.fileList = list.map((item) => {
              if (typeof item === 'string') {
                item = { name: this.getFileName(item), url: item };
              }
              item.uid = item.uid || new Date().getTime() + temp++;
              return item;
            });
          } else {
            this.fileList = [];
            return [];
          }
        },
        deep: true,
        immediate: true,
      },
    },
    mounted() { },
    methods: {
      // 获取文件名称
      getFileName(name) {
        // 如果是url那么取最后的名字 如果不是直接返回
        if (name.lastIndexOf('/') > -1) {
          return name.slice(name.lastIndexOf('/') + 1);
        } else {
          return name;
        }
      },
    },
  };
</script>

<style>
  .upload-file-list .el-upload-list__item {
    border: 1px solid #e4e7ed;
    line-height: 2;
    margin-bottom: 10px;
    position: relative;
  }

  .upload-file-list .ele-upload-list__item-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: inherit;
  }

  .ele-upload-list__item-content-action .el-link {
    margin-right: 10px;
  }
</style>